---
sidebar_class_name: hidden
---

# SQL

This example demonstrates the use of the `SQLDatabaseChain` for answering questions over a SQL database.

import CodeBlock from "@theme/CodeBlock";
import SqlDBExample from "@examples/chains/sql_db_legacy.ts";
import SqlDBSqlOutputExample from "@examples/chains/sql_db_sql_output_legacy.ts";
import SqlDBSAPHANAExample from "@examples/chains/sql_db_saphana_legacy.ts";
import SqlDBSqlCustomPromptExample from "@examples/chains/sql_db_custom_prompt_legacy.ts";

This example uses Chinook database, which is a sample database available for SQL Server, Oracle, MySQL, etc.

:::info
These are legacy docs. It is now recommended to use LCEL over legacy implementations.

Looking for the LCEL docs? Click [here](/docs/modules/chains/popular/sqlite).
:::

## Set up

First install `typeorm`:

```bash npm2yarn
npm install typeorm
```

Then install the dependencies needed for your database. For example, for SQLite:

```bash npm2yarn
npm install sqlite3
```

Currently, LangChain.js has default prompts for
Postgres, SQLite, Microsoft SQL Server, MySQL, and SAP HANA.

Finally follow the instructions on https://database.guide/2-sample-databases-sqlite/ to get the sample database for this example.

import IntegrationInstallTooltip from "@mdx_components/integration_install_tooltip.mdx";

<IntegrationInstallTooltip></IntegrationInstallTooltip>

```bash npm2yarn
npm install @langchain/openai
```

<CodeBlock language="typescript">{SqlDBExample}</CodeBlock>

You can include or exclude tables when creating the `SqlDatabase` object to help the chain focus on the tables you want.
It can also reduce the number of tokens used in the chain.

```typescript
const db = await SqlDatabase.fromDataSourceParams({
  appDataSource: datasource,
  includesTables: ["Track"],
});
```

If desired, you can return the used SQL command when calling the chain.

<CodeBlock language="typescript">{SqlDBSqlOutputExample}</CodeBlock>

## SAP Hana

Here's an example of using the chain with a SAP HANA database:

<CodeBlock language="typescript">{SqlDBSAPHANAExample}</CodeBlock>

## Custom prompt

You can also customize the prompt that is used. Here is an example prompting the model to understand that "foobar" is the same as the Employee table:

<CodeBlock language="typescript">{SqlDBSqlCustomPromptExample}</CodeBlock>
